package com.jeeplus.modules.api.log;

import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;

import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import com.alibaba.fastjson.JSONObject;

import lombok.extern.slf4j.Slf4j;

@ControllerAdvice(basePackages = "com.jeeplus.modules.api")
@Slf4j
public class LogRequestAdvice implements RequestBodyAdvice{
	
	@Override
	public boolean supports(MethodParameter methodParameter, Type targetType,
			Class<? extends HttpMessageConverter<?>> converterType) {
		return true;
	}

	@Override
	public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter,
			Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
		Method method = parameter.getMethod();
		log.info("请求路径:{}.{}, 请求参数:{}", method.getDeclaringClass().getSimpleName(), method.getName(), JSONObject.toJSONString(body));
		return body;
	}

	@Override
	public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
			Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
		return inputMessage;
	}

	@Override
	public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
			Class<? extends HttpMessageConverter<?>> converterType) {
		Method method = parameter.getMethod();
		log.info("请求路径:{}.{}, 请求参数:{}", method.getDeclaringClass().getSimpleName(), method.getName(), JSONObject.toJSONString(body));
		return body;
	}

}
